<template>
	<div class="container">
		<el-card>
			<div slot="header">
				<!-- 面包屑 -->
				<el-breadcrumb separator-class="el-icon-arrow-right">
				  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
				  <el-breadcrumb-item>{{isPublish}}文章</el-breadcrumb-item>
				</el-breadcrumb>
			</div>
			<!-- 表单 -->
			<el-form ref="publishRef" :model="publishForm" :rules="publishRules" label-width="80px">
			  <el-form-item label="标题：" prop="title">
			    <el-input v-model="publishForm.title"></el-input>
			  </el-form-item>
				<el-form-item label="内容：" prop="content">
					<!-- <el-input v-model="publishForm.content"></el-input> -->
					<el-tiptap
						v-model="publishForm.content"
						:extensions="extensions"
						lang="zh"
						placeholder="Write something …"
						height="400"></el-tiptap>
				</el-form-item>
				<el-form-item label="封面：">
					<el-radio-group v-model="publishForm.cover.type">
						<el-radio :label="1">单图</el-radio>
						<el-radio :label="3">三图</el-radio>
						<el-radio :label="0">无图</el-radio>
						<el-radio :label="-1">自动</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item>
					<template v-if="publishForm.cover.type > 0">
					<!-- v-model 双向绑定 和一下代码一样！具有同步功能 默认事件为input 参数为 value -->
					<!-- :cover="publishForm.cover.images[index]" -->
					<!-- @cover="getCover(index, $event)" -->
						<cover
							:key="index"
							v-for="(cover, index) in publishForm.cover.type"
							:coverIndex="index"
							v-model="publishForm.cover.images[index]"
						 />
					</template>
				</el-form-item>
				<el-form-item label="频道：" prop="channel_id">
					<el-select v-model="publishForm.channel_id" clearable placeholder="请选择">
						<el-option
							v-for="(channel, i) in channels"
							:key="i"
							:label="channel.name"
							:value="channel.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onPublish(false)">{{isPublish}}</el-button>
					<el-button type="default" @click="onPublish(true)">存入草稿</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script>
	import { getChannels, publishArticle, getArticleById, updateArticleById } from '@/api/article.js'
	// element-tiptap（富文本）中文文档： https://github.com/Leecason/element-tiptap/blob/master/README_ZH.md
	import {
		ElementTiptap,
		Doc,
		Text,
		Paragraph,
		Heading,
		Bold,
		Underline,
		Italic,
		Strike,
		ListItem,
		BulletList,
		OrderedList,
		Image,
		TextAlign,
		Table,
		TableHeader,
		TableCell,
		TableRow,
		TextColor
	 } from 'element-tiptap'
	 // import element-tiptap 样式
	import 'element-tiptap/lib/index.css'
	import cover from './components/Cover.vue'
	export default {
		data () {
			return {
				// 发表文章表单数据对象
				publishForm: {
					// 标题
					title: '',
					// 内容
					content: '',
					// 封面对象
					cover: {
						type: 1, // 封面类型
						images: [] // 封面数组
					},
					// 频道id
					channel_id: ''
				},
				// 频道数据数组
				channels: [],
				// 发布文章表单规则对象
				publishRules: {
					title: [
						{ required: true, message: '请输入标题', trigger: 'blur' },
						{ min: 5, max: 30, message: '长度在 5 到 30 个字符', trigger: 'blur' }
					],
					content: [
						{ required: true, message: '请输入内容', trigger: 'blur' }
					],
					channel_id: [
						{ required: true, message: '请选择频道', trigger: 'change' }
					]
				},
				// 富文本编辑器配置项
				// 编辑器的 extensions
				// 它们将会按照你声明的顺序被添加到菜单栏和气泡菜单中
				extensions: [
					new Doc(),
					new Text(),
					new Paragraph(),
					new Heading({ level: 3 }),
					new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
					new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
					new Italic(),
					new Strike(),
					new TextAlign(),
					new TextColor(),
					new ListItem(),
					new BulletList(),
					new OrderedList(),
					new Image(),
					new Table(),
					new TableHeader(),
					new TableCell(),
					new TableRow()
				]
			}
		},
		created () {
			this._loadChannels()

			// 判断是否为修改文章
			if (this.$route.query.id) {
				// 调用查询文章
				this._loadArticle()
			}
		},
		methods: {
			// 加载频道数据
			_loadChannels () {
				getChannels().then(({ data: res }) => {
					console.log(res)
					this.channels = res.data.channels
				}).catch(err => {
					this.$message.error('获取文章频道失败：' + err)
				})
			},
			// 发布/修改文章
			onPublish (draft = false) {
				// 表单预验证
				this.$refs.publishRef.validate((valid) => {
					// 判断是否通过
					if (!valid) return this.$message.error('请按照表单规则编写文章！')

					const articleId = this.$route.query.id
					// 判断是修改文章还是发布新文章
					if (articleId) {
						console.log('执行修改')
						// 编辑文章
						updateArticleById(articleId, this.publishForm, draft).then(({ data: res }) => {
							this.$message.success(`${draft ? '存入草稿' : '修改文章'}成功！`)
							this.$router.push('/article')
						}).catch(err => {
							this.$message.error(`${draft ? '存入草稿' : '修改文章'}失败！` + err)
						})
					} else {
						console.log('执行新建')
						// 发布新文章
						publishArticle(this.publishForm, draft).then(({ data: res }) => {
							this.$message.success(`${draft ? '存入草稿' : '发布文章'}成功！`)
							this.$router.push('/article')
						}).catch(err => {
							this.$message.error(`${draft ? '存入草稿' : '发布文章'}失败！` + err)
						})
					}
				})
			},
			// 加载指定文章
			_loadArticle () {
				getArticleById(this.$route.query.id).then(({ data: res }) => {
					this.publishForm.title = res.data.title
					this.publishForm.content = res.data.content
					this.publishForm.channel_id = res.data.ch_id
					this.publishForm.cover.type = res.data.aut_id
					this.publishForm.cover.images[0] = res.data.aut_photo
					console.log(res)
				})
			}
		},
		computed: {
			isPublish () {
				const mode = this.$route.query.id
				return mode ? '修改' : '发表'
			}
		},
		components: {
			'el-tiptap': ElementTiptap,
			cover
		},
		watch: {
			// // 监听封面个数的变化
			'publishForm.cover.type' () {
				const index = this.publishForm.cover.type
							const length = this.publishForm.cover.images.length

				this.publishForm.cover.images.splice(index, length)
			}
		}
	}
</script>

<style lang="less" scoped>

</style>
